import axios from "axios";
import { ElLoading } from "element-plus";
class MJCrequest {
  constructor(config) {
    this.instance = axios.create(config);
    this.interceptors = config.interceptors;
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    );
    // this.instance.interceptors.request.use(
    //   this.interceptors?.requestInterceptor,
    //   this.interceptors?.requestInterceptorCatch
    // );

    // this.instance.interceptors.response.use(
    //   this.interceptors.responseInterceptor,
    //   this.interceptors.responseInterceptorCatch
    // );

    this.instance.interceptors.request.use(
      (config) => {
        console.log("全部请求成功");
        this.loading = ElLoading.service({
          locak: true,
          text: "正在请求数据...",
          background: "rgba(0,0,0,0.5)",
        });
        return config;
      },
      (err) => {
        console.log("全部请求失败");
        console.log(err);
        return err;
      }
    );

    this.instance.interceptors.response.use(
      (res) => {
        console.log("全局的响应成功");
        this.loading?.close();
        return res;
      },
      (err) => {
        console.log("全部响应失败");
        console.log(err);
        this.loading?.close();
        return err;
      }
    );
  }
  request(config) {
    return new Promise((resolve, reject) => {
      this.instance
        .request(config)
        .then((res) => {
          if (res.status != 200) {
            console.log(res);
            reject(res);
            return;
          }
          resolve(res);
        })
        .catch((err) => {
          //请求失败触发
          reject(err);
          return err;
        });
    });
  }

  get(config) {
    return this.request({ ...config, method: "GET" });
  }
  post(config) {
    return this.request({ ...config, method: "POST" });
  }
  delete(config) {
    return this.request({ ...config, method: "DELETE" });
  }
  patch(config) {
    return this.request({ ...config, method: "PATCH" });
  }
  put(config) {
    return this.request({ ...config, method: "PUT" });
  }
  delete(config) {
    return this.request({ ...config, method: "DELETE" });
  }
}

export default MJCrequest;
